package com.abocode.aichat.app.auth;


import com.abocode.aichat.app.constant.ErrorCode;
import com.abocode.aichat.app.utils.EncryptionUtils;
import com.abocode.aichat.app.utils.StringUtil;
import com.abocode.aichat.app.vo.RereadHttpServletRequestWrapper;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by guanxf on 2015/12/16.
 */
@Component
public class RereadHttpServletRequestFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        try {

           String url= request.getRequestURI();
            if(!url.contains("update-avatar") && !request.getMethod().equals("GET") ){
                RereadHttpServletRequestWrapper rereadHttpServletRequestWrapper= new RereadHttpServletRequestWrapper((HttpServletRequest)request);
                request=rereadHttpServletRequestWrapper;
            }
            chain.doFilter(request, response);

        }catch (Exception e){
            Map<String, Object> map=   buildResultMap(ErrorCode.COMM_READ_REQEUST_VALUE_ERROR, String.format("非法请求reread http servlet request body is Exception"));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.print(EncryptionUtils.toBody(map));
            out.flush();
        }
    }



    private Map<String, Object> buildResultMap(String status, String message) {
        Map<String, Object> result = new HashMap<>();
        result.put("status", status);
        result.put("time", StringUtil.getDateTime(new Date()));
        result.put("message", message);
        return result;
    }
}
